package com.management.department.teacherinfosystem.Service;

import com.management.department.teacherinfosystem.DTO.MemberDTO;
import com.management.department.teacherinfosystem.DTO.ProjectSubmitDTO;
import com.management.department.teacherinfosystem.DTO.FundingDTO;
import com.management.department.teacherinfosystem.Entity.TeachingProject;
import com.management.department.teacherinfosystem.Entity.TeachingProjectMember;
import com.management.department.teacherinfosystem.Entity.Attachment;
import com.management.department.teacherinfosystem.Entity.User;
import com.management.department.teacherinfosystem.Entity.ProjectFunding;
import com.management.department.teacherinfosystem.Repository.TeachingProjectRepository;
import com.management.department.teacherinfosystem.Repository.TeachingProjectMemberRepository;
import com.management.department.teacherinfosystem.Repository.AttachmentRepository;
import com.management.department.teacherinfosystem.Repository.UserRepository;
import com.management.department.teacherinfosystem.Repository.ProjectFundingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private TeachingProjectRepository projectRepository;
    @Autowired
    private TeachingProjectMemberRepository memberRepository;
    @Autowired
    private AttachmentRepository attachmentRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ProjectFundingRepository fundingRepository;

    @Value("${file.upload.project-dir}")
    private String projectUploadDir;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveProjectWithMembersAndFile(ProjectSubmitDTO dto, MultipartFile[] files) throws Exception {
        // 1. 保存项目主表
        TeachingProject project = new TeachingProject();
        project.setName(dto.getName());
        project.setProjectNumber(dto.getProjectNumber());
        project.setProjectType(dto.getProjectType());
        project.setLevel(dto.getLevel());
        // 设置负责人ID：如果leaderName为空，使用当前登录用户
        Long leaderId;
        if (dto.getLeaderName() == null || dto.getLeaderName().trim().isEmpty()) {
            // 从Spring Security获取当前用户
            org.springframework.security.core.Authentication auth = 
                org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
            if (auth != null) {
                String currentUsername = auth.getName();
                User currentUser = userRepository.findByUsername(currentUsername).orElse(null);
                if (currentUser != null) {
                    leaderId = currentUser.getId();
                } else {
                    throw new RuntimeException("当前用户不存在: " + currentUsername);
                }
            } else {
                throw new RuntimeException("未登录或认证信息丢失");
            }
        } else {
            // 用 leaderName 查用户对象
            User leader = userRepository.findByName(dto.getLeaderName());
            if (leader == null) {
                throw new RuntimeException("负责人不存在: " + dto.getLeaderName());
            }
            leaderId = leader.getId();
        }
        project.setLeaderId(leaderId);
        
        // 自动生成项目编号：TIP + 年份 + 月份 + 6位递增序号
        if (dto.getProjectNumber() == null || dto.getProjectNumber().trim().isEmpty()) {
            String autoProjectNumber = generateProjectNumber();
            project.setProjectNumber(autoProjectNumber);
        } else {
            project.setProjectNumber(dto.getProjectNumber());
        }
        
        project.setStatus("申报中");  // 根据流程图，初始状态为申报中

        // 日期转换 - 同时检查null和空字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        project.setStartDate(isValidDateString(dto.getStartDate()) ? sdf.parse(dto.getStartDate()) : null);
        project.setEndDate(isValidDateString(dto.getEndDate()) ? sdf.parse(dto.getEndDate()) : null);

        project.setApplicationDate(isValidDateString(dto.getApplicationDate()) ? sdf.parse(dto.getApplicationDate()) : null);
        project.setApprovalDate(isValidDateString(dto.getApprovalDate()) ? sdf.parse(dto.getApprovalDate()) : null);
        project.setApprovalDepartment(dto.getApprovalDepartment());
        
        // 结题信息
        project.setFinishDate(isValidDateString(dto.getFinishDate()) ? sdf.parse(dto.getFinishDate()) : null);
        project.setFinishType(dto.getFinishType());
        project.setFinishLevel(dto.getFinishLevel());
        project.setFinishResults(dto.getFinishResults());

        project.setCreatedAt(new Date());
        project.setUpdatedAt(new Date());
        TeachingProject saved = projectRepository.save(project);

        // 1.5. 保存经费信息
        if (dto.getFundings() != null && !dto.getFundings().isEmpty()) {
            for (FundingDTO fundingDto : dto.getFundings()) {
                if (fundingDto.getAmount() != null && fundingDto.getPurpose() != null && !fundingDto.getPurpose().trim().isEmpty()) {
                    ProjectFunding funding = new ProjectFunding(saved.getId(), fundingDto.getAmount(), fundingDto.getPurpose());
                    fundingRepository.save(funding);
                }
            }
        }

        // 2. 保存成员表
        if (dto.getMembers() != null) {
            for (MemberDTO m : dto.getMembers()) {
                TeachingProjectMember member = new TeachingProjectMember();
                member.setProjectId(saved.getId());
                
                // 如果有工号，必须能找到对应用户
                if (m.getStaffNo() != null && !m.getStaffNo().trim().isEmpty()) {
                    User u = userRepository.findByStaffNo(m.getStaffNo()).orElse(null);
                    if (u == null) {
                        throw new RuntimeException("工号 " + m.getStaffNo() + " 不存在，请检查后重新输入");
                    }
                    member.setUserId(u.getId());
                    member.setDepartment(u.getDepartment());
                } else {
                    // 没有工号时，使用当前登录用户信息（适用于负责人等情况）
                    member.setUserId(null);
                    member.setDepartment(m.getDepartment());
                }
                
                member.setRole(m.getRole());
                member.setCreatedAt(new Date());
                memberRepository.save(member);
            }
        }

        // 3. 保存附件表及文件
        if (files != null && files.length > 0) {
            File dir = new File(projectUploadDir);
            if (!dir.exists()) dir.mkdirs();
            for (MultipartFile file : files) {
                if (file == null || file.isEmpty()) continue;
                String saveName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
                File dest = new File(projectUploadDir + saveName);
                file.transferTo(dest);

                Attachment attachment = new Attachment();
                attachment.setFileName(file.getOriginalFilename());
                attachment.setFileUrl(projectUploadDir + saveName);
                attachment.setRelatedType("teaching_project");
                attachment.setRelatedId(saved.getId());
                attachment.setUploadedBy(1L); // 可替换为当前用户ID
                attachment.setUploadedAt(new Date());
                attachmentRepository.save(attachment);
            }
        }

        return saved.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProject(Long id) throws Exception {
        TeachingProject project = projectRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("项目不存在"));

        // 删除关联数据
        // 1. 删除项目成员
        memberRepository.deleteByProjectId(id);
        
        // 2. 删除项目经费
        fundingRepository.deleteByProjectId(id);
        
        // 3. 删除项目附件
        List<Attachment> attachments = attachmentRepository.findByRelatedTypeAndRelatedId("teaching_project", id);
        for (Attachment attachment : attachments) {
            // 删除物理文件
            try {
                String fileUrl = attachment.getFileUrl();
                if (fileUrl != null && !fileUrl.isEmpty()) {
                    // 从URL中提取文件路径（假设fileUrl包含完整路径或相对路径）
                    // 这里需要根据实际的文件存储逻辑来处理
                    // 暂时跳过物理文件删除，只删除数据库记录
                }
            } catch (Exception e) {
                // 文件删除失败不影响数据库记录删除
                e.printStackTrace();
            }
        }
        attachmentRepository.deleteByRelatedIdAndRelatedType(id, "teaching_project");
        
        // 4. 删除项目本身
        projectRepository.delete(project);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resubmitProject(Long id, ProjectSubmitDTO dto, MultipartFile[] files) throws Exception {
        TeachingProject project = projectRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("项目不存在"));

        if (!"已驳回".equals(project.getStatus())) {
            throw new RuntimeException("只有已驳回的项目可以重新提交！");
        }

        // 1. 更新主表字段
        project.setName(dto.getName());
        project.setProjectType(dto.getProjectType());
        project.setLevel(dto.getLevel());

        // 负责人处理：与首次申报一致，若未提供负责人姓名，则默认当前登录用户为负责人
        Long leaderId;
        if (dto.getLeaderName() == null || dto.getLeaderName().trim().isEmpty()) {
            org.springframework.security.core.Authentication auth =
                org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
            if (auth != null) {
                String currentUsername = auth.getName();
                User currentUser = userRepository.findByUsername(currentUsername).orElse(null);
                if (currentUser != null) {
                    leaderId = currentUser.getId();
                } else {
                    throw new RuntimeException("当前用户不存在: " + currentUsername);
                }
            } else {
                throw new RuntimeException("未登录或认证信息丢失");
            }
        } else {
            User leader = userRepository.findByName(dto.getLeaderName());
            if (leader == null) throw new RuntimeException("负责人不存在: " + dto.getLeaderName());
            leaderId = leader.getId();
        }
        project.setLeaderId(leaderId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        project.setStartDate(isValidDateString(dto.getStartDate()) ? sdf.parse(dto.getStartDate()) : null);
        project.setEndDate(isValidDateString(dto.getEndDate()) ? sdf.parse(dto.getEndDate()) : null);
        project.setUpdatedAt(new Date());
        
        // 根据项目类型决定重新提交后的状态
        // 如果是结题审核被驳回的项目，重新提交后应该回到"结题审核中"状态
        // 如果是申报被驳回的项目，重新提交后回到"申报中"状态
        // 简化判断：主要检查项目是否有结题信息
        boolean hasFinishInfo = (project.getFinishDate() != null) 
                               || (project.getFinishType() != null && !project.getFinishType().trim().isEmpty());
        
        System.out.println("DEBUG: 重新提交项目ID=" + id);
        System.out.println("DEBUG: finishDate=" + project.getFinishDate());
        System.out.println("DEBUG: finishType=" + project.getFinishType());
        System.out.println("DEBUG: hasFinishInfo=" + hasFinishInfo);
        
        if (hasFinishInfo) {
            // 有结题信息，说明是结题审核被驳回，重新提交后回到"结题审核中"
            System.out.println("DEBUG: 设置状态为结题审核中");
            project.setStatus("结题审核中");
        } else {
            // 没有结题信息，说明是申报被驳回，重新提交后回到"申报中"
            System.out.println("DEBUG: 设置状态为申报中");
            project.setStatus("申报中");
        }

        // 1.5. 处理经费（删除旧，新增新）
        fundingRepository.deleteByProjectId(id);
        if (dto.getFundings() != null && !dto.getFundings().isEmpty()) {
            for (FundingDTO fundingDto : dto.getFundings()) {
                if (fundingDto.getAmount() != null && fundingDto.getPurpose() != null && !fundingDto.getPurpose().trim().isEmpty()) {
                    ProjectFunding funding = new ProjectFunding(id, fundingDto.getAmount(), fundingDto.getPurpose());
                    fundingRepository.save(funding);
                }
            }
        }

        // 2. 处理成员（删除旧，新增新）
        memberRepository.deleteByProjectId(id);
        if (dto.getMembers() != null) {
            for (MemberDTO m : dto.getMembers()) {
                TeachingProjectMember member = new TeachingProjectMember();
                member.setProjectId(id);
                
                // 如果有工号，必须能找到对应用户
                if (m.getStaffNo() != null && !m.getStaffNo().trim().isEmpty()) {
                    User u = userRepository.findByStaffNo(m.getStaffNo()).orElse(null);
                    if (u == null) {
                        throw new RuntimeException("工号 " + m.getStaffNo() + " 不存在，请检查后重新输入");
                    }
                    member.setUserId(u.getId());
                    member.setDepartment(u.getDepartment());
                } else {
                    member.setUserId(null);
                    member.setDepartment(m.getDepartment());
                }
                
                member.setRole(m.getRole());
                member.setCreatedAt(new Date());
                memberRepository.save(member);
            }
        }

        // 3. 处理附件（删除旧，新增新）
        attachmentRepository.deleteByRelatedIdAndRelatedType(id, "teaching_project");
        if (files != null && files.length > 0) {
            File dir = new File(projectUploadDir);
            if (!dir.exists()) dir.mkdirs();
            for (MultipartFile file : files) {
                if (file == null || file.isEmpty()) continue;
                String saveName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
                File dest = new File(projectUploadDir + saveName);
                file.transferTo(dest);

                Attachment attachment = new Attachment();
                attachment.setFileName(file.getOriginalFilename());
                attachment.setFileUrl(projectUploadDir + saveName);
                attachment.setRelatedType("teaching_project");
                attachment.setRelatedId(id);
                attachment.setUploadedBy(1L); // 可替换为当前用户ID
                attachment.setUploadedAt(new Date());
                attachmentRepository.save(attachment);
            }
        }

        projectRepository.save(project);
    }

    /**
     * 检查日期字符串是否有效（非null且非空字符串）
     */
    private boolean isValidDateString(String dateStr) {
        return dateStr != null && !dateStr.trim().isEmpty();
    }

    /**
     * 自动生成项目编号：TIP + 年份 + 月份 + 6位递增序号
     * 格式：TIP202501000001
     */
    private String generateProjectNumber() {
        Date now = new Date();
        SimpleDateFormat yearMonthFormat = new SimpleDateFormat("yyyyMM");
        String yearMonth = yearMonthFormat.format(now);
        
        // 简化实现：TIP + 年月 + 随机6位数字
        String prefix = "TIP" + yearMonth;
        long randomSequence = System.currentTimeMillis() % 1000000;
        
        return String.format("%s%06d", prefix, randomSequence);
    }
}
